package de.duester.genealogy.adapter;

import java.util.List;

import de.duester.genealogy.R;
import de.duester.genealogy.model.Date;
import de.duester.genealogy.model.Event;
import de.duester.genealogy.model.Person;
import de.duester.genealogy.model.service.EventService;
import de.duester.genealogy.model.service.PersonService;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class FamilyOverviewAdapter extends ArrayAdapter<Person> {
	private Activity activity;
	private List<Person> persons;
	private List<String> relationships;

	public FamilyOverviewAdapter(Context context, int textViewResourceId,
			List<Person> persons, List<String> relationships) {
		super(context, textViewResourceId, persons);
		activity = (Activity) context;
		this.persons = persons;
		this.relationships = relationships;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View v;

		if (convertView == null) {
			LayoutInflater li = activity.getLayoutInflater();
			v = li.inflate(R.layout.family_list_element, null);
		} else
			v = convertView;

		TextView tvRelationship = (TextView) v.findViewById(R.id.tvRelationship);
		TextView tvPerson = (TextView) v.findViewById(R.id.tvPerson);
		TextView tvDates = (TextView) v.findViewById(R.id.tvDates);

		String relationship = relationships.get(position);
		tvRelationship.setText(relationship);

		Person person = persons.get(position);
		tvPerson.setText(person.toString());

		String s = "";
		List<Event> birthEvents = PersonService.getEvents(person, "birth", "child");
		if (birthEvents.size() > 0) {
			Date birthDate = EventService.getDate(birthEvents.get(0), "date");
			s = birthDate.toString();
		}
		if (!PersonService.isAlive(person)) {
			Date deathDate = EventService.getDate(PersonService
					.getEvents(person, "death").get(0), "date");
			s += " - " + deathDate.toString();
		}
		tvDates.setText(s);
		
		v.setBackgroundResource(R.drawable.list_element);

		return v;
	}

	@Override
	public Person getItem(int position) {
		return persons.get(position);
	}

}
